//
//  JD_CacheTool.m
//  Jared_AFN_Cache
//
//  Created by Jared on 2017/1/18.
//  Copyright © 2017年 Jared. All rights reserved.
//

#import "JD_CacheTool.h"
#import "JDMD5.h"

#define kCachePath ([NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject])
/**
 缓存的有效期  单位是s
 */
#define kJDCache_Expire_Time (3600*24)

@implementation JD_CacheTool
+ (void)cacheForData:(NSData *)data fileName:(NSString *)fileName{
    NSString *path = [kCachePath stringByAppendingPathComponent:[JDMD5 md5:fileName]];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [data writeToFile:path atomically:YES];
    });
}

+ (NSData *)getCacheFileName:(NSString *)fileName{
    NSString *path = [kCachePath stringByAppendingPathComponent:[JDMD5 md5:fileName]];
    return [[NSData alloc] initWithContentsOfFile:path];
}

+ (NSInteger)getSize{
    //获取AFN的缓存大小
    NSInteger afnSize = [self getAFNSize];
    return afnSize;
}

+ (NSInteger)getAFNSize{
    NSInteger size = 0;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtPath:kCachePath];
    for (NSString *fileName in fileEnumerator) {
        NSString *filePath = [kCachePath stringByAppendingPathComponent:fileName];
        NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        size += [attrs fileSize];
    }
    return size;
}

+ (void)clearCache{
    [self clearAFNCache];
}

+ (void)clearAFNCache{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtPath:kCachePath];
    for (NSString *fileName in fileEnumerator) {
        NSString *filePath = [kCachePath stringByAppendingPathComponent:fileName];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

+ (BOOL)isExpire:(NSString *)fileName{
    NSString *path = [kCachePath stringByAppendingPathComponent:[JDMD5 md5:fileName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *attributesDict = [fileManager attributesOfItemAtPath:path error:nil];
    NSDate *fileModificationDate = attributesDict[NSFileModificationDate];
    NSTimeInterval fileModificationTimestamp = [fileModificationDate timeIntervalSince1970];
    NSTimeInterval nowTimestamp = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    return ((nowTimestamp-fileModificationTimestamp)>kJDCache_Expire_Time);
}



@end









